package com.za.plugin.transfer.func;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;

// 把 pow() 转为 power()
public class PowFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return clearSpace(sql).contains("pow(");
    }

    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll("pow\\s*\\(", "pow(");
    }

    @Override
    public String transfer(String sql) {
        MySqlStatementParser parser = new MySqlStatementParser(sql);
        SQLStatement sqlStatement = parser.parseStatement();
        sqlStatement.accept(new MySqlASTVisitorAdapter() {
            @Override
            public boolean visit(SQLMethodInvokeExpr expr) {
                if (expr.getMethodName().equalsIgnoreCase("pow")) {
                    expr.setMethodName("power");
                }
                return super.visit(expr);
            }
        });
        return SQLUtils.toMySqlString(sqlStatement);

    }
}



//        sql = clearSpace(sql);
//        sql = sql.replace("pow(", "power(");
//        return sql;